<template>
	<view>
		<z-paging ref="paging" v-model="dataList" :refresher-out-rate="0.8" auto-scroll-to-top-when-reload
			safe-area-inset-bottom bg-color="#fff"
			empty-view-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/987eadb1d50949a0a7e25dbbd99abe30.png"
			@query="queryList">
			<view slot="top">
				<view class="search">
					<u-search placeholder="搜索订单" v-model="keyword" bgColor="#E1E1E1" color="#333"
						placeholderColor="#999999" clearabled height="64rpx" @custom="keywordSearch"
						:actionStyle="actionStyle" />
				</view>
			</view>

			<view class="item" v-for="(item, index) in dataList" :key="index">
				<view class="item_time flex_wrap row_between">
					<u-text :text="$u.timeFormat(item.createTime)" size="28rpx" color="#777777" />
					<view style="
                            width: 200rpx;
                            display: flex;
                            align-items: center;
                        ">
						<u-text :text="
                                getInterface === '1'
                                    ? statusConstans[item.orderStatus]
                                    : orderRefundStatus[item.orderRefundStatus]
                            " color="#588BF3" size="28rpx" align="right" />
					</view>
				</view>

				<!-- 成为会员订单 -->
				<view v-if="item.goodsName == '购买会员'" class="item_detail flex_wrap row_between"
					@click.stop="toDetail(item)">
					<u-image height="156rpx" width="156rpx"
						src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/9081de61452d4e28ade187b32ac8dc24.png"
						mode="‌aspectFill" radius="8rpx" />
					<view>
						<text class="total">{{ item.goodsName }}</text>
						<u-gap height="16rpx" />
						<view class="flex_wrap row_between">
							<u-text :text="'￥' + item.goodsPrice" size="28rpx" color="#333"></u-text>
							<u-text :text="'x' + item.goodsCount" size="28rpx" align="right" color="#777"></u-text>
						</view>
					</view>
				</view>
				<view v-for="(items, indexs) in item.orderGoodsList" :key="indexs"
					class="item_detail flex_wrap row_between" @click.stop="toDetail(item)">
					<u-image height="156rpx" width="156rpx" :src="JSON.parse(items.goodsSnapshot).thumbnail"
						mode="aspectFill" radius="8rpx" />
					<view>
						<text class="total">{{ items.goodsName }}</text>
						<view class="detail_tt flex_wrap">
							<text>{{
                                items.goodsSnapshot.skuSimpleSpecs || " "
                            }}</text>
						</view>
						<u-gap height="16rpx" />
						<view class="flex_wrap row_between">
							<u-text :text="'￥' + items.goodsPrice" size="28rpx" color="#333"></u-text>
							<u-text :text="'x' + items.goodsCount" size="28rpx" align="right" color="#777"></u-text>
						</view>
					</view>
				</view>
				<view class="price">
					<u-text :text="`${
                            item.receiveName ||
                            item.consigneeInfo.consigneeName ||
                            ' '
                        }  ${
                            item.receivePhone ||
                            item.consigneeInfo.consigneeMobile ||
                            ' '
                        }`" size="28rpx" align="left" margin="18rpx 4rpx" prefixIcon="account-fill" color="#588BF3"
						iconStyle="font-size: 40rpx;color:#588BF3"></u-text>
					<view>
						<text>实付：</text>
						<text class="price_t">￥{{
                                item.orderDealAmountCent == 0
                                    ? 0
                                    : formatDecimal(
                                          numDiv(item.orderDealAmountCent, 100)
                                      )
                            }}</text>
					</view>
				</view>
				<view class="">
					<u-text v-if="item.promoteCommission" :text="
                            '推广佣金：' +
                            numDiv(item.promoteCommission, 100) +
                            '元'
                        " type="warning" size="28rpx" margin="0 28rpx" />
				</view>
				<view class="button flex_wrap row_between" style="
                        padding: 0 24rpx 16rpx;
                        justify-content: space-between;
                    " v-if="getInterface === '1'">
					<view style="display: inline-block">
						<!-- <u-text
							@click="connectCustomSerice"
                            v-if="item.orderStatus === 2"
                            text="联系客服"
                            color="#333"
                            size="24rpx"
                            prefixIcon="/pages_shop1/static/img/order/customer_service.png"
                            :iconStyle="{ width: '42rpx', height: '42rpx' }"
                        /> -->
						<u-text @click="to_orderClass(item)" v-if="
                                (item.orderStatus === 2 ||
                                    item.orderStatus === 3) &&
                                item.goodsSnapshot.videoSeries
                            " text="课程学习" color="#588BF3" size="28rpx"
							prefixIcon="/pages_shop1/static/img/order/orderClass.png" :iconStyle="{
                                width: '44rpx',
                                height: '44rpx',
                                marginRight: '10rpx',
                            }" />
						<u-text v-if="
                                (item.orderStatus === 2 ||
                                    item.orderStatus === 3) &&
                                item.goodsSnapshot.handleFlag == 'CHICKEN_FLAG'
                            " @click="to_orderChicken()" text="福鸡乐园" color="#F79B37" size="28rpx"
							prefixIcon="/pages_shop1/static/img/order/orderChicken.png" :iconStyle="{
                                width: '44rpx',
                                height: '44rpx',
                                marginRight: '10rpx',
                            }" />
					</view>

					<view class="flex_wrap row_right">
						<view v-if="[1, 2].includes(item.orderStatus)">
							<!-- <button type="default" class="cancelOrderBtn" v-if="item.orderStatus === 4" >删除订单</button> -->
							<button type="default" class="cancelOrderBtn" @click="refund(item.orderNum)" v-if="
                                    item.orderStatus === 2 &&
                                    !item.goodsSnapshot.videoSeries && item.goodsName !== '购买会员' && item.sevenDaysInMs
                                ">
								申请退款
							</button>
							<button type="default" class="cancelOrderBtn" v-if="item.orderStatus === 1"
								@click.stop="cancelOrder(item)">
								取消订单
							</button>
						</view>
						<view v-if="item.orderStatus === 1" style="margin-left: 30rpx">
							<button type="primary" class="payBtn" @click="pay(item)">
								付款
							</button>
						</view>
					</view>
				</view>
			</view>
		</z-paging>
		<u-modal :show="showCancelModal" title="提示" content="是否确认取消订单" @confirm="confirmCancelOrder"
			@cancel="cancelConfirm" showCancelButton>
			<view style="text-align: center">是否确认取消订单</view>
		</u-modal>

		<u-popup :show="showService" @close="closeService" @open="openService" mode="center" round="20rpx" closeable>
			<view style="width: 610rpx; height: 324rpx; padding-top: 80rpx">
				<view class="" style="
                        text-align: center;
                        font-size: 16px;
                        font-weight: normal;
                        line-height: 22px;
                    ">十蜂健康客服热线</view>
				<view class="mobile" style="text-align: center; margin-top: 20rpx">{{ servicePhone }}</view>
				<view class="line" style="
                        width: 446rpx;
                        height: 1px;
                        border: 1px solid #f3f3f3;
                        background-color: #bbb;
                        position: relative;
                        left: calc(50% - 223rpx);
                        margin-top: 20rpx;
                    "></view>
				<u-button type="primary" text="呼叫" @click="call()"
					customStyle="margin-top:42rpx;width:160rpx;height:44rpx;font-size: 24rpx;border-radius:22rpx" />
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getListBySalesman,
		getRefundListBySalesman,
		cancelOrder,
		getOrderPay,
		getProtocolByCode,
		orderRefund,
		getRememberHealthManagered
	} from "@/api/order.js";
	import {
		queryPromotionAmount
	} from "@/api/shopSalesman.js";
	import {
		numAdd,
		numSub,
		numMulti,
		numDiv,
	} from "@/js_sdk/nl-precisionNum/precisionNum.js";
	import {
		formatDecimal
	} from "@/utils/index.js";
	import {
		mapGetters
	} from "vuex";
	import caches from "@/config/caches.js";
	import {
		chickUrl
	} from "@/config/tendIdConfig.js";
	import {
		encryption
	} from "@/utils/encryption.js";
	export default {
		data() {
			return {
				promotionAmountNum: "",
				showService: false,
				numAdd,
				numSub,
				numMulti,
				numDiv,
				showCancelModal: false,
				formatDecimal: formatDecimal,
				actionStyle: {
					fontSize: "28rpx",
					color: "#333",
				},
				statusConstans: {
					1: "待付款",
					2: "待发货",
					3: "已完成",
					4: "交易关闭",
					5: "已退款",
					7: "退款中",
				},
				orderRefundStatus: {
					1: "部分退款",
					2: "全部退款",
				},
				keyword: "",
				show: false,
				status: "",
				navList: [{
						name: "全部",
						interface: "1", //1:查订单列表接口 2:查退款订单列表接口
						status: "", //查询条件 空字符串为查询全部 1:查待付款 2查待领取 3查已完成 4查退款
					},
					{
						name: "已付款",
						interface: "1", //1:查订单列表接口 2:查退款订单列表接口
						status: "3", //查询条件 空字符串为查询全部 1:查待付款 2查待领取 3查已完成 4查退款
					},
					{
						name: "待付款",
						interface: "1", //1:查订单列表接口 2:查退款订单列表接口
						status: "1", //查询条件 空字符串为查询全部 1:查待付款 2查待领取 3查已完成 4查退款
					},
					{
						name: "客户订单",
						interface: "1", //1:查订单列表接口 2:查退款订单列表接口
						scene: 1,
						status: "3",
					}
				],
				dataList: [],
				cellIconStyle: {
					width: "36rpx",
					height: "36rpx",
					marginRight: "14rpx",
				},
				cellTitleStyle: {
					fontSize: "28rpx",
					color: "#333",
				},
				servicePhone: "",
				currentOrderNum: "",
				payWay: 1, //1:'微信支付' || 2:'积分支付'
				authority: this.$store.getters?.authority ?? "customer",
			};
		},
		computed: {
			...mapGetters(["userInfo", "isLogin"]),
			getInterface() {
			    return 1;
			},
		},
		beforeDestroy() {
			if (this.isLogin) {
				uni.removeStorageSync("loginBackUrl");
				uni.removeStorageSync("loginBackUrlOption");
			}
		},
		onLoad(e) {
			// 解决微信扫码登录 新用户登录跳回 该页面
			var pages = getCurrentPages(); // 获取栈实例
			console.log("当pages" + pages.length);
			if (pages.length === 2) {
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				console.log(pages, "路由当前页面路径" + currentRoute);
				let currentPage = pages[pages.length - 1]["$page"]["fullPath"]; //当前页面路径(带参数)
				console.log("当前打开路径" + currentPage);
				uni.setStorageSync("loginBackUrl", currentPage);
			}

			this.showType();
			this.current = e?.current ?? 0;
			console.log("e :>> ", e);
			getProtocolByCode("CUSTOMER_SERVICE_HOTLINE").then((res) => {
				const {
					code,
					data: {
						customerServicePhone = ""
					},
				} = res;
				if (code === 200) this.servicePhone = customerServicePhone;
			});
		},
		onShow() {
			this.$refs.paging.reload();
		},
		methods: {
			refund(orderNum) {
				const that = this;
				uni.showModal({
					title: "",
					content: "确定要申请该单退款吗？",
					success({
						confirm,
						cancel
					}) {
						if (confirm) {
							orderRefund(orderNum).then((res) => {
								uni.$u.toast("申请成功！");
								that.$refs.paging.reload();
							});
						}
					},
				});
			},
			to_orderClass(item) {
				this.videoSeries = item.goodsSnapshot.videoSeries;
				uni.$u.route({
					type: "redirectTo",
					url: "pages_operate/videoPage/detail",
					params: {
						recordType: 9,
						videoSeries: this.videoSeries,
						btnShow: 1,
					},
				});
			},
			promotionAmount() {
				queryPromotionAmount().then((res) => {
					if (res.code === 200) {
						this.promotionAmountNum = res.data;
					} else {
						console.log("请求失效列表失败");
					}
				});
			},
			to_orderChicken() {
				const phone = uni.getStorageSync(caches.PHONE);
				// 使用 uni.request 替换 wx.request，支持跨平台
				uni.request({
					url: chickUrl + "/api/v1/auth/phone-login",
					method: "POST",
					data: {
						...encryption({
							user_phone: phone,
						}),
					},
					success: (res) => {
						this.token = res.data.data.token;
						// 使用 uni.navigateTo 替换 wx.navigateTo，支持跨平台
						uni.navigateTo({
							url: `/pages_shop1/pay/chickenDetail/jump?url=${encodeURIComponent(
                            chickUrl + "/go"
                        )}&api_token=${this.token}`,
						});
					},
					fail: (err) => {},
				});
			},
			closeService() {
				this.showService = false;
			},
			openService() {
				this.showService = true;
			},
			toreciveList(item) {
				uni.$u.route({
					url: "pages_shop1/order/pick_up_record/index",
					params: {
						salesmanId: item.salesmanId,
						orderNum: item.orderNum,
					},
				});
			},
			async pay(item) {
				const that = this;
				that.goodsType = item.goodsSnapshot.handleFlag;
				that.orderPlatform = item.orderPlatform;
				this.payButtonLoading = true;
				const {
					data
				} = await getOrderPay(item.orderNum);
				uni.requestPayment({
					provider: "wxpay",
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.packageValue,
					signType: "MD5",
					paySign: data.paySign,
					success: function(res) {
						if (res.errMsg === "requestPayment:ok") {
							if (
								that.goodsType == "CHICKEN_FLAG" &&
								that.orderPlatform == "2"
							) {
								uni.$u.route({
									type: "redirectTo",
									url: "pages_shop1/pay/chickenDetail/index",
									params: {
										status: "success",
										orderNum: data.outTradeNo,
										productCount: item.goodsCount,
									},
								});
							} else {
								// uni.$u.route({
								//     // type: 'redirectTo',
								//     url: "pages_shop1/pay/payResult/index",
								//     params: {
								//         status: "success",
								//         orderNum: data.outTradeNo,
								//     },
								// });
								that.getIsWeChat()
							}
						}
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					},
				});
			},
			getIsWeChat() {
				getRememberHealthManagered().then((res) => {
					if (res.code === 200 && res.data) {
						uni.$u.route({
							type: "redirectTo",
							url: "pages_shop1/addWeChat/index",
							params: {
								wcName: res.data.nickName,
								wcImgUrl: res.data.wechatCpQrCode
							},
						});
					} else {
						uni.$u.route({
							type: "redirectTo",
							url: "pages_shop1/order/order_list/index",
						});
					}
				});
			},
			toRecive(item) {
				if (!item.isReceive) {
					uni.showToast({
						title: "暂无可领取券码",
						icon: "error",
					});
					return;
				}
				uni.$u.route({
					url: "/pages_shop1/order/coupon/index",
					params: {
						orderNum: item.orderNum,
					},
				});
			},
			cancelOrder(item) {
				this.currentOrderNum = item.orderNum;
				this.showCancelModal = true;
			},
			cancelConfirm() {
				this.currentOrderNum = "";
				this.showCancelModal = false;
			},
			async confirmCancelOrder() {
				const that = this;
				const params = {
					orderNum: this.currentOrderNum,
				};
				const result = await cancelOrder(params);
				uni.showToast({
					title: "订单取消成功",
					icon: "success",
					success() {
						that.showCancelModal = false;
						that.currentOrderNum = "";
						that.$refs.paging.reload();
					},
				});
			},
			toDetail(item) {
				uni.$u.route({
					url: "/pages_shop1/order/order_detail/order_detail",
					params: {
						id: item.orderNum,
						detailStatus: 0, //1：用户中心进去的  0：客户端领取记录进去的
					},
				});
			},
			keywordSearch() {
				this.$refs.paging.reload();
			},
			call() {
				uni.makePhoneCall({
					phoneNumber: this.servicePhone,
					success: (res) => {},
					fail: (res) => {},
				});
			},
			connectCustomSerice() {
				this.showService = true;
			},
			showType() {
				// 使用 uni.setNavigationBarColor 替换 wx.setNavigationBarColor，支持跨平台
				uni.setNavigationBarColor({
					frontColor: "#000000",
					backgroundColor: "#ffffff",
				});
			},
			orderDetail() {
				uni.navigateTo({
					url: "../order_detail/order_detail",
				});
			},
			async queryList(pageNo, pageSize) {
				const status = this.getStatus;
				const params = {
					pageNum: pageNo,
					pageSize: pageSize,
					info: this.keyword,
					scene:1
				};
				const result = await getListBySalesman(params);
				const rows = result.data.rows.map((item) => {
					if (item.goodsSnapshot) {
						const goodsSnapshot =
							item.goodsSnapshot &&
							JSON.parse(item.goodsSnapshot);
						const simpleSpecs =
							(goodsSnapshot.simpleSpecs &&
								JSON.parse(goodsSnapshot.simpleSpecs)) ||
							null;
						const skuSpecs =
							(goodsSnapshot.skuSpecs &&
								JSON.parse(goodsSnapshot.skuSpecs)) ||
							null;
						item.goodsSnapshot = goodsSnapshot;
						item.goodsSnapshot.simpleSpecs = simpleSpecs || null;
						item.goodsSnapshot.skuSpecs = skuSpecs || null;
					}
					if (item.consigneeInfo)
						item.consigneeInfo = JSON.parse(item.consigneeInfo);

					if (item.payTime) {
						// 假设下单时间，格式为时间戳，单位毫秒，需替换成真实值
						const orderTimeStamp = Date.parse(item.payTime);
						// 获取当前时间戳
						const currentTimeStamp = new Date().getTime();
						// 7天对应的毫秒数
						const sevenDaysInMs = 7 * 24 * 60 * 60 * 1000;
						if ((currentTimeStamp - orderTimeStamp) > sevenDaysInMs) {
							console.log("已过7天，不可退款");
							item.sevenDaysInMs = false
						} else {
							console.log("在7天内，可申请退款");
							item.sevenDaysInMs = true
						}
					}
					return item;
				});
				this.$refs.paging.completeByTotal(rows, result.data.total);
			},
		},
	};
</script>

<style lang="scss" scoped>
	.search {
		padding: 32rpx 28rpx;
	}

	.item {
		margin: 20rpx 28rpx 0;
		box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.08);
		border-radius: 12rpx;
	}

	.item_time {
		height: 80rpx;
		border-bottom: 2rpx solid #f3f3f3;
		padding: 0 24rpx;
	}

	.item_detail {
		padding: 26rpx 20rpx 0;

		image {
			width: 180rpx;
			height: 180rpx;
			border-radius: 8rpx;
		}
	}

	.total {
		display: block;
		width: 450rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
	}

	.detail_tt {
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #666666;

		text {
			margin-right: 10rpx;
		}
	}

	.price {
		border-top: 2rpx solid #f3f3f3;
		height: 72rpx;
		text-align: right;
		font-size: 24rpx;
		color: #333333;
		line-height: 72rpx;
		margin-right: 12rpx;
		font-weight: 400;
		display: flex;
		padding: 0 20rpx;
		margin-top: 28rpx;
		justify-content: flex-end;

		.price_t {
			font-size: 32rpx;
			font-weight: 400;
			color: #ff0000;
		}
	}

	.payBtn {
		width: 158rpx;
		height: 52rpx;
		line-height: 52rpx;
		font-size: 24rpx;
		margin-right: 0;
		margin-left: 0;
		background: #588bf3;
		color: #ffffff;
		border-radius: 22rpx;
		font-weight: 400;
	}

	.payBtn::after {
		border: none;
	}

	.cancelOrderBtn {
		width: 158rpx;
		height: 52rpx;
		line-height: 52rpx;
		font-size: 24rpx;
		font-weight: 400;
		border: 1px solid #e3e3e3;
		border-radius: 22rpx;
		outline: none;
	}

	.cancelOrderBtn::after {
		border: none;
	}

	.customerSerivce {
		width: 32rpx;
		height: 32rpx;
	}
</style>